<?php
/**
 * Created by PhpStorm.
 * Date: 2016/10/17
 * Time: 16:27
 * User: 潘国兴
 * Email: denispan@outlook.com
 */

namespace app\common\lib;
set_time_limit(0);
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Crond extends Command
{
    protected function configure()
    {
        $this->setName('Cron')->setDescription('计划任务---start---0000-----------');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        $output->writeln("已经执行计划任务---start---9200000-----------");
    }

    public function doCron()
    {
        // 记录开始运行的时间
        $GLOBALS['_beginTime'] = microtime(TRUE);

        /* 永不超时 */
        ini_set('max_execution_time', 0);
        $time   = time();
        $exe_method = [];
        $crond_list = config('crond');   //获取第四步的文件配置，根据自己版本调整一下
        $crond_list = config('crond.config');
        var_dump($crond_list);
        $sys_crond_timer = Config::get('sys_crond_timer');
        var_dump($sys_crond_timer);
        foreach ( $sys_crond_timer as $format )
        {
            $key = date($format, ceil($time));
            //print_r( $crond_list[$key])."\n";
            if (is_array(@$crond_list[$key]) )
            {
                $exe_method = array_merge($exe_method, $crond_list[$key]);
                echo var_dump($exe_method)."\n";
                echo var_dump($crond_list[$key])."\n";
            }
        }
        if (!empty($exe_method))
        {
            foreach ($exe_method as $method)
            {
                if(!is_callable($method))
                {
                    //方法不存在的话就跳过不执行
                    //continue;
                }

                echo "执行crond --- {$method}()\n";
                $runtime_start = microtime(true);
                //\app\command\controller\Test::firstTest();
                //call_user_func();
                //call_user_func($method);
                call_user_func($method);

                $runtime = microtime(true) - $runtime_start;

                echo "{$method}(), 执行时间: {$runtime}\n\n";
                \app\command\Test::add_timed_task_log($method);
            }

            $time_total = microtime(true) - $GLOBALS['_beginTime'];
            echo "total:{$time_total}\n";
        }
    }
}